package com.xm_jd.utils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class BaseServlet extends HttpServlet {
	private ThreadLocal<HttpServletRequest> request = new ThreadLocal<>();
	private ThreadLocal<HttpServletResponse> response = new ThreadLocal<>();
	private ThreadLocal<Map<String,Object>> params = new ThreadLocal<>();
	
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			//1、设置字符集
			request.setCharacterEncoding("utf-8");
			response.setCharacterEncoding("utf-8");
			
			this.request.set(request);
			this.response.set(response);
			this.params.set(new HashMap<>());
			//设置根路径
			request.setAttribute("_ctx", request.getContextPath() + "/");

			//3、session参数转存
			HttpSession session = request.getSession();
			//从作用域中取出存的值
			Map<String,Object> flashParams = 
					(Map<String,Object>)session.getAttribute("_flash_");
			if(flashParams!=null) {
				for (Entry<String,Object> e : flashParams.entrySet()) {
					//转存到request
					request.setAttribute(e.getKey(), e.getValue());
				}
				//将session清空
				session.removeAttribute("_flash_");
			}
			
			//4、统一异常处理
			//做完前置操作后，执行父类的service，系统帮我们判断是doget还是dopost
			super.service(request, response);
		} catch (Exception e) {
			e.printStackTrace();
			//错误信息存入作用域，显示到一个error页面
			request.setAttribute("err", e.getMessage());
			this.forward("error");
		}
	}

	//2、转发或重定向封装
	/**
	 * 转发
	 * @throws IOException 
	 * @throws ServletException 
	 */
	public void forward(String path) throws ServletException, IOException {

		request.get().getRequestDispatcher("/WEB-INF/jsps/"+ path +".jsp").forward(request.get(), response.get());

	}
	
	/**
	 * 重定向
	 * @throws IOException 
	 */
	public void redirect(String path) throws IOException {
		//将值存入session
		if(!params.get().isEmpty()) {
			request.get().getSession().setAttribute("_flash_", params.get());
		}
		response.get().sendRedirect(request.get().getContextPath() + path);
	}
	
	/**
	 * 添加参数
	 * @param key
	 * @param value
	 */
	public void addParam(String key,Object value) {
		this.params.get().put(key, value);
	}
}
